//
//  InfoViewController.m
//  ZzzzyManProject
//
//  Created by mac on 16/3/4.
//  Copyright © 2016年 ZzzzyMan@. All rights reserved.
//

#import "InfoViewController.h"
#import "UserLoginViewController.h"
#import <AFNetworking.h>
#import "InfoTableView.h"
#import "InfoItemArrow.h"
#import "UserInfo.h"
//#import "UMSocial.h"
#import <UIButton+WebCache.h>
#import <MBProgressHUD.h>
//Mob分享
#import <ShareSDKUI/ShareSDKUI.h> 
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKExtension/ShareSDK+Extension.h>

#define ViewSize self.view.bounds.size
#define TopViewHeight 250

@interface InfoViewController ()

@property (nonatomic,strong) UIView * topView;
@property (nonatomic,strong) UILabel * infoLabel;
@property (nonatomic,strong) UIImageView * backGroudView;
@property (nonatomic,strong) UIButton * iconBtn;
@property (nonatomic,strong) UILabel * nameLabel;
@property (nonatomic,strong) InfoTableView * infoTableView;
@property (nonatomic,strong) MBProgressHUD * HUD;

@end

@implementation InfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.frame = CGRectMake(0, 0, 300,667);

    
    //检查用户是否登陆
    UserInfo * userInfo = [UserInfo loadUserInfo];
    if (userInfo) {
        //如果用户已经登陆,从本地加载数据,并禁用登陆按钮
        self.nameLabel.text = userInfo.name;
        [self.iconBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:userInfo.iconUrl] forState:UIControlStateNormal];
        self.iconBtn.userInteractionEnabled = false;
    }
    
    
    [self setTopView];
    [self setInfoTableView];
    [self registerNotification];
    [self setHUD];
}

#pragma mark - 初始化HUD
- (void)setHUD {
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.mode = MBProgressHUDModeText;
}

#pragma mark - 注册通知
- (void)registerNotification {
    //点击cell切换控制器
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(modalVC:) name:@"modalVC" object:nil];
    //修改用户昵称
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updataName:) name:@"updataName" object:nil];
    //用户注销
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logOff:) name:@"logOff" object:nil];
    //关闭通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logOff:) name:@"logOff" object:nil];
    //Mob分享
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mobShare:) name:@"mobShare" object:nil];
    //清除缓存
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cleanCache:) name:@"cleanCache" object:nil];
}

#pragma mark - 通知方法
#pragma mark - Mob分享
- (void)mobShare:(NSNotification *)notification {
    
    
    //1.创建分享参数
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    UIImage * image = [UIImage imageNamed:@"MarvelNewsimg"];
    NSArray* imageArray = @[image];
    if (imageArray)
    {
        [shareParams SSDKSetupShareParamsByText:@"比tmUM好用多了!fk"
                                         images:imageArray
                                            url:[NSURL URLWithString:@"http://www.mob.com"]
                                          title:@"Mob分享测试"
                                           type:SSDKContentTypeAuto];
    }
    
    //2.分享菜单
    [ShareSDK showShareActionSheet:nil items:nil shareParams:shareParams onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
        switch (state) {
            case SSDKResponseStateSuccess:
            {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                    message:nil
                                                                   delegate:nil
                                                          cancelButtonTitle:@"确定"
                                                          otherButtonTitles:nil];
                [alertView show];
                break;
            }
            case SSDKResponseStateFail:
            {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                    message:[NSString stringWithFormat:@"%@", error]
                                                                   delegate:nil
                                                          cancelButtonTitle:@"确定"
                                                          otherButtonTitles:nil];
                [alertView show];
                break;
            }
            case SSDKResponseStateCancel:
            {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
                                                                    message:nil
                                                                   delegate:nil
                                                          cancelButtonTitle:@"确定"
                                                          otherButtonTitles:nil];
                [alertView show];
                break;
            }
            default:
                break;
        }

    }];

    
//    [ShareSDK share:SSDKPlatformSubTypeWechatTimeline parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
//        switch (state) {
//            case SSDKResponseStateSuccess:
//            {
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
//                                                                    message:nil
//                                                                   delegate:nil
//                                                          cancelButtonTitle:@"确定"
//                                                          otherButtonTitles:nil];
//                [alertView show];
//                break;
//            }
//            case SSDKResponseStateFail:
//            {
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败"
//                                                                    message:[NSString stringWithFormat:@"%@", error]
//                                                                   delegate:nil
//                                                          cancelButtonTitle:@"确定"
//                                                          otherButtonTitles:nil];
//                [alertView show];
//                break;
//            }
//            case SSDKResponseStateCancel:
//            {
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
//                                                                    message:nil
//                                                                   delegate:nil
//                                                          cancelButtonTitle:@"确定"
//                                                          otherButtonTitles:nil];
//                [alertView show];
//                break;
//            }
//            default:
//                break;
//        }
//
//    }];
//    
//    //2、分享
//    [ShareSDK share:SSDKPlatformTypeSinaWeibo
//         parameters:shareParams
//     onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error)
//     {
//         switch (state) {
//             case SSDKResponseStateSuccess:
//             {
//                 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
//                                                                     message:nil
//                                                                    delegate:nil
//                                                           cancelButtonTitle:@"确定"
//                                                           otherButtonTitles:nil];
//                 [alertView show];
//                 break;
//             }
//             case SSDKResponseStateFail:
//             {
//                 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败"
//                                                                     message:[NSString stringWithFormat:@"%@", error]
//                                                                    delegate:nil
//                                                           cancelButtonTitle:@"确定"
//                                                           otherButtonTitles:nil];
//                 [alertView show];
//                 break;
//             }
//             case SSDKResponseStateCancel:
//             {
//                 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
//                                                                     message:nil
//                                                                    delegate:nil
//                                                           cancelButtonTitle:@"确定"
//                                                           otherButtonTitles:nil];
//                 [alertView show];
//                 break;
//             }
//             default:
//                 break;
//         }
//     }];
}

#pragma mark - 点击Cell切换对应控制器
- (void)modalVC:(NSNotification *)notification {
    
    if (![self isLogin]) {
        
        [self isLogin];
        
    }else {
        
        //根据模型的控制器属性,模态出对应控制器
        InfoItemArrow * arrow = (InfoItemArrow *)notification.object;
        UIViewController * vc = [[arrow.Controller alloc] init];
        vc.title = arrow.title;
        [self presentViewController:vc animated:YES completion:nil];
        
    }
}

#pragma mark - 退出登陆
- (void)logOff:(NSNotification *)notification {
    
    if ([self isLogin]) {
        [self setHUD];
        self.HUD.labelText = @"退出登陆成功";
        [self.HUD showAnimated:YES whileExecutingBlock:^{
            sleep(2);
        }completionBlock:^{
            
            [self.HUD removeFromSuperview];
            self.nameLabel.text = @"点击头像登陆";
            [_iconBtn setBackgroundImage:[UIImage imageNamed:@"IconPlaceholder"] forState:UIControlStateNormal];
            self.iconBtn.userInteractionEnabled = true; //开启按钮交互
            
            //清除本地配置文件
            NSFileManager * manager = [NSFileManager defaultManager];
            NSString * path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"userInfo.plist"];
            NSError * error = [[NSError alloc] init];
            [manager removeItemAtPath:path error:&error];
            
        }];
    }else {
        [self isLogin];
    }
}

#pragma mark - 登陆成功:更新个人信息
- (void)updataName:(NSNotification *)notification {
    UserInfo * userInfo = (UserInfo *)notification.object;
    
    //提示用户登陆成功
    [self setHUD];
    self.HUD.labelText = @"登陆成功";
    [self.HUD showAnimated:YES whileExecutingBlock:^{
        sleep(2);
    } completionBlock:^{
        [self.HUD removeFromSuperview];
        self.nameLabel.text = userInfo.name;
        [self.iconBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:userInfo.iconUrl] forState:UIControlStateNormal];
        self.iconBtn.userInteractionEnabled = false;
    }];
    
    
}

#pragma mark - 清除缓存
- (void)cleanCache:(NSNotification *)notification {
    
    //清除缓存
    [SDWebImageManager.sharedManager.imageCache calculateSizeWithCompletionBlock:^(NSUInteger fileCount, NSUInteger totalSize) {
        [[[SDWebImageManager sharedManager] imageCache] clearDisk];
        [[[SDWebImageManager sharedManager] imageCache] clearMemory];
        [[NSURLCache sharedURLCache] removeAllCachedResponses];
        
        //提示用户清除完毕
        [self setHUD];
        [self.view addSubview:self.HUD];
        self.HUD.mode = MBProgressHUDModeText;
        self.HUD.labelText = @"清除完成";
        [self.HUD showAnimated:YES whileExecutingBlock:^{
            sleep(2);
        }];
    }];
}


#pragma mark - 检查是否登陆
- (BOOL)isLogin {
    UserInfo * userInfo = [UserInfo loadUserInfo];
    if (userInfo) {
        return true;
    }else {
        MBProgressHUD * HUD = [[MBProgressHUD alloc] init];
        [self.view addSubview:HUD];
        HUD.mode = MBProgressHUDModeText;
        HUD.labelText = @"请先登陆";
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(2);
        }];
        return false;
    }
}


#pragma mark - 设置view
- (void)setTopView {
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ViewSize.width, 220)];
    self.topView.backgroundColor = [[UIColor alloc] initWithRed:231/255.0 green:231/255.0 blue:231/255.0 alpha:1];
    
    [self.topView addSubview:self.infoLabel]; //个人信息
    [self.topView addSubview:self.backGroudView]; //头像底层(伪圆环效果)
    [self.topView addSubview:self.iconBtn]; //头像
    [self.topView addSubview:self.nameLabel]; //名字
    
    [self.view addSubview: self.topView];
}

#pragma mark - 设置选项界面
- (void)setInfoTableView {
    InfoTableView * infoTableView = [[InfoTableView alloc] initWithFrame:CGRectMake(0, 220, ViewSize.width, ViewSize.height - 220)];
    self.infoTableView = infoTableView;
    self.infoTableView.showsVerticalScrollIndicator = false;
    
    [self.view addSubview:infoTableView];
}

#pragma mark - 点击头像监听方法
- (void)iconBtnClick{
    UserLoginViewController *userLogin = [[UserLoginViewController alloc] init];
    [self presentViewController:userLogin animated:YES completion:nil];
}





#pragma mark - 懒加载子控件
- (UILabel *)infoLabel {
    if (!_infoLabel) {
        _infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, ViewSize.width, 40)];
        _infoLabel.text = @"个人信息";
        _infoLabel.textAlignment = NSTextAlignmentCenter;
        _infoLabel.textColor = [UIColor blackColor];
        _infoLabel.font = [UIFont boldSystemFontOfSize:18];
    }
    return _infoLabel;
}

- (UIImageView *)backGroudView {
    if (!_backGroudView) {
        _backGroudView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 105, 105)];
        _backGroudView.center = CGPointMake(ViewSize.width/2, TopViewHeight/2);
        _backGroudView.backgroundColor = [UIColor blackColor];
        _backGroudView.layer.cornerRadius = 52.5;
        _backGroudView.layer.masksToBounds = true;
    }
    return _backGroudView;
}

- (UIButton *)iconBtn {
    if (!_iconBtn) {
        _iconBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        _iconBtn.center = CGPointMake(ViewSize.width/2 , TopViewHeight/2);
        [_iconBtn setBackgroundImage:[UIImage imageNamed:@"IconPlaceholder"] forState:UIControlStateNormal];
        _iconBtn.layer.cornerRadius = 50;
        _iconBtn.layer.masksToBounds = true;
        [_iconBtn addTarget:self action:@selector(iconBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _iconBtn;
}

- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 180, ViewSize.width, 40)];
        _nameLabel.font = [UIFont boldSystemFontOfSize:16];
        _nameLabel.textAlignment = NSTextAlignmentCenter;
        _nameLabel.text = @"点击头像登陆";
        _nameLabel.textColor = [UIColor colorWithRed:100/225.0 green:100/225.0 blue:100/225.0 alpha:1];
    }
    return _nameLabel;
}
@end
